/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 驿站代收开通审核
 */
import React, { useRef, useCallback, useEffect } from 'react';
import {
  searchPhoneDevice,
  getPullingBlackLog,
  operatePullingBlack,
} from '@/services/operatorManagement';
import { removeSMSBlack } from '@/services/sms/blackDeductMoney';
import ProTable from '@ant-design/pro-table';
import { Input, Button, message, Popconfirm } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ConnectState } from '@/models/connect';
import { useSelector } from 'umi';
import { TableListItem, platform, sourceOptions, getSourceOptions } from '../types/BlackList.d';
import styles from './CommonTable.less';
import ProForm, { ModalForm, ProFormTextArea } from '@ant-design/pro-form';

interface BlackListTableType {
  activeKey: string;
  type: string;
}

interface RefuseModalProps {
  children: JSX.Element;
  tableRef: ActionType | undefined;
  item: TableListItem;
}

const RefuseModal: React.FC<RefuseModalProps> = ({ item, children, tableRef }) => {
  const { id, device_id, device_model, device_phone = '' } = item;
  return (
    <ModalForm
      title='拉黑原因'
      trigger={children}
      width={480}
      onFinish={async (values) => {
        const params = {
          operate: 'add',
          id,
          reason: values.text,
          device_id,
          device_model,
          phone: device_phone,
        };
        const { code, msg } = await operatePullingBlack(params);
        if (code == 0) {
          message.success(msg);
          tableRef?.reload();
          return true;
        }
        message.error(msg);
        return false;
      }}
    >
      <ProForm.Group>
        <ProFormTextArea width='xl' name='text' placeholder='请输入拉黑原因' allowClear />
      </ProForm.Group>
    </ModalForm>
  );
};

const BlackListTable = ({ type, activeKey }: BlackListTableType) => {
  const actionRef = useRef<ActionType>();
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const isMobile = winSize === 'xs';
  const cancelPullingBlack = async (item: TableListItem) => {
    const {
      id = '',
      device_id = '',
      device_model = '',
      device_phone = '',
      reason = '',
      source = '',
      kb_id,
      cm_id,
    } = item;
    const params =
      source === 'device'
        ? {
            operate: 'del',
            id,
            reason,
            device_id,
            device_model,
            phone: device_phone,
          }
        : {
            kb_id,
            cm_id,
          };

    const { code, msg } =
      source === 'device' ? await operatePullingBlack(params) : await removeSMSBlack(params);
    if (code == 0) {
      message.success(msg);
      actionRef?.current?.reload();
      return true;
    }
    message.error(msg);
    return false;
  };
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '来源',
      dataIndex: 'source',
      hideInTable: true,
      search: type === 'operation' ? false : undefined,
      valueType: 'select',
      initialValue: 'device',
      fieldProps: {
        options: getSourceOptions(),
      },
    },
    {
      title: '账号',
      hideInTable: true,
      dataIndex: 'keywords',
      renderFormItem: () => {
        return <Input name='keywords' placeholder='请输入手机号' />;
      },
    },
    {
      title: '设备did',
      dataIndex: 'device_id',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '设备型号',
      dataIndex: 'device_model',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '平台标识',
      dataIndex: 'platform_flag',
      align: 'center',
      search: false,
      ellipsis: true,
      render: (_, record) => {
        return platform[record.platform_flag];
      },
    },
    {
      title: '拉黑账户',
      dataIndex: 'device_phone',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '来源',
      dataIndex: 'source',
      align: 'center',
      search: false,
      ellipsis: true,
      render: (_, record) => {
        return sourceOptions[record.source];
      },
    },
    {
      title: '拉黑原因',
      dataIndex: 'reason',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '操作人',
      dataIndex: 'by_user',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '拉黑时间',
      dataIndex: 'created_at',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'is_in_black',
      key: 'option1',
      valueType: 'option',
      fixed: 'right',
      width: isMobile ? 50 : 130,
      render: (_, record) => {
        return !record.is_in_black ? (
          <RefuseModal key='refuse' item={record} tableRef={actionRef.current}>
            <a key='link'>拉黑</a>
          </RefuseModal>
        ) : (
          <Popconfirm title='确定取消拉黑' onConfirm={cancelPullingBlack.bind(null, record)}>
            <a key='link'>取消拉黑</a>
          </Popconfirm>
        );
      },
    },
  ];

  const requestTableData = useCallback(
    async (values) => {
      const { current, pageSize, keywords, source } = values;
      if (type === 'operation' && !keywords) return;
      const reqData: {
        page: number;
        size: number;
        phone: string;
        source?: string;
      } = {
        page: current,
        size: pageSize,
        phone: keywords,
        source,
      };
      const requestFunc = type === 'operation' ? searchPhoneDevice : getPullingBlackLog;
      const { code, data, msg } = await requestFunc(reqData);
      if (code == 0) {
        const formatList = data?.list?.map((item: { device_phone: any }) => ({
          ...item,
          device_phone: item.device_phone || keywords || '',
        }));
        return { data: formatList, total: data.count };
      } else {
        message.error(msg);
        return {};
      }
    },
    [type],
  );

  useEffect(() => {
    if (activeKey !== type) return;
    actionRef.current?.reload();
  }, [activeKey, type]);

  return (
    <>
      <ProTable<TableListItem>
        actionRef={actionRef}
        rowKey='id'
        className={styles.table}
        request={requestTableData}
        columns={columns}
        options={false}
        pagination={{
          pageSize: 20,
          showQuickJumper: false,
          showSizeChanger: false,
        }}
        scroll={{ x: 1200 }}
        search={{
          optionRender: (_, { form }) => [
            <Button
              key='phone'
              type='primary'
              onClick={() => {
                form?.submit();
              }}
            >
              搜索
            </Button>,
            <Button
              key='phone'
              type='primary'
              onClick={() => {
                if (actionRef.current?.reset) {
                  actionRef.current?.reset();
                }
              }}
            >
              重置
            </Button>,
          ],
        }}
      />
    </>
  );
};

export default BlackListTable;
